<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/3
 * Time: 16:09
 */
namespace Institution\Controller;
use Think\Controller;
use User\Model\UserModel;

class AccountController extends AdminController{
    public function _empty($action=index){
        C('URL_MODEL');
        //print_R($action);exit;
        //获取当前机构的所有用户
        $data = I('get.');
        if($data['typeid']){
            //$map['typeid'] = $data['typeid'];
            $map = self::getUserType($data['typeid']);
        }
        $map = self::getParam($data);
        $map['department_id'] = DEPARTMENT_ID;
       /* $userModel = new UserModel();
        $userList = $userModel->where(array('department'=>DEPARTMENT_ID))->select();*/
        $list = $this->lists(M('Kjcx'),$map);
        $this->assign('meta_title', '组合信息');
        if($action=="export"){//生成年度详细报告
            if(!$list){
                $this->error('数据为空');
            }
            $time                   = (date('Y',time())-1).'-12-31';
            $where['intime']        = array('gt',$time);
            $where['department_id'] = DEPARTMENT_ID;
           // $where['process_id']    = array(array('gt',12),array('lt',15));
            $datas = M('Kjcx')->where($where)->select();
            $this->dataExport($datas,1);
        }elseif($action=='download'){//下载
            $datas = M('Kjcx')->where($map)->select();
            $this->dataExport($datas,2);
        }
        $list = self::fomartFileIds($list);
        $this->assign('_list', $list);
        $this->assign('data',$data);
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display();
    }

    /**
     * 格式化查新附件id
     * @param $list
     * @return mixed
     */
    function fomartFileIds($list){
        foreach($list as $k=> $v){
            if($v['cx_file_ids']){
                $filedsId = explode(',',$v['cx_file_ids']);
                foreach($filedsId as $kk=>$vv){
                    $list[$k]['fileId'][$kk][fid] =$vv;
                }
            }
        }
        return $list;
    }
    /**
     * 获取机构人员角色
     * @param int $typeid
     * @return array
     */
    function  getUserType($typeid=0){
        if($typeid){
            $userModel = M('User');
            $userInfo  = $userModel->find($typeid);
            switch($userInfo['$typeid']){
                case 10:
                    $map['cx_user_name'] = $userInfo['id'];//查新员
                    break;
                case 11:
                    $map['sh_user_name'] = $userInfo['id'];//审核员
                    break;
                case 12:
                    $map['sf_user_name'] = $userInfo['id'];//收费员
                    break;
                case 14:
                    $map['zs_user_name'] = $userInfo['id'];//终审人员
                    break;
                default:
                    $map = array();
                    break;
            }
            return $map;
        }
    }

    /**
     * 返回查询条件
     * @param array $data
     * @return mixed
     */
    function getParam($data=array()){
        if($data['cxfw']){
            $map['cxfw'] = $data['cxfw'];
        }
        if($data['cxmd']){
            $map['cxmd'] = array('LIKE',"%$data[cxmd]%");
        }
        if($data['xmjb']){
            $map['xmjb'] = $data['xmjb'];
        }
        if($data['starttime'] && $data['endtime']){
            $endtime = date('Y-m-d H:i:s',strtotime($data['endtime'])+86400);
            $map['intime']= array(array('gt',$data['starttime']),array('lt',$endtime));
        }

        if($data['starttime'] && !$data['endtime']){
            $map['intime']= array('gt',$data['starttime']);
        }

        if(!$data['starttime'] && $data['endtime']){
            $endtime = date('Y-m-d H:i:s',strtotime($data['endtime'])+86400);
            $map['intime']= array('lt',$endtime);
        }
        return $map;
    }

    /**
     * 处理需要导出的excel
     * @param array $list
     * @param int $type
     */
    protected function dataExport($list = array(),$type=1){
        $goods_list = $list;
        $data = array();
        foreach ($goods_list as $k=>$goods_info){
            if($type==1){//生成年度报表
                $data[$k][wtrname]      = $goods_info['wtrname'];//委托人姓名
                $data[$k][wtdw]         = $goods_info['wtdw'];//委托单位
                $data[$k][wtremail]     = $goods_info['wtremail'];//委托人邮箱
                $data[$k][xmmc]         = $goods_info['xmmc'];//项目名称（中文）
                $data[$k][xmmcen]       = $goods_info['xmmcen'];//项目名称（英文）
                $data[$k][cxmd]         = self::getCxmds($goods_info['cxmd']);//查新目的
                $data[$k][xxcxmd]       = $goods_info['xxcxmd'];//详细查新目的
                $data[$k][cxfw]         = self::getArea($goods_info['cxfw']);//查新地域
                $data[$k][xmjb]         = self::getLevel($goods_info['xmjb']);//项目级别
                $data[$k][lqrq]         = $goods_info['lqrq'];//期望完成日期
                $data[$k][fkfs]         = $goods_info['fkfs']&&$goods_info['fkfs']==1?'网上支付':'汇款凭证上传';//付款方式
                $data[$k][kpdw]         = $goods_info['kpdw'];//发票抬头
                $data[$k][qbfs]         = $goods_info['qbfs']&&$goods_info['qbfs']==1?'自取':'快递';//取报告方式
                $data[$k][txdz]         = $goods_info['txdz'];//通信地址
                $data[$k][lxryzbm]      = $goods_info['lxryzbm'];//邮政编码
                $data[$k][show_add_cxd] = $goods_info['show_add_cxd'];//科学技术要点
                $data[$k][cxyq]         = self::getCxyq($goods_info['cxyq']);
                $data[$k][keywords_cn]  = $goods_info['keywords_cn'];//检索词
                $data[$k][contents]     = $goods_info['contents'];//其他说明
                $data[$k][intime]       = $goods_info['intime'];//委托日期
                $data[$k][zs_user_name] = getUserTrueNameById($goods_info['zs_user_name']);//完成人
                $data[$k][cxh]          = $goods_info['cxh'];//查新号
                $data[$k][zfy]          = $goods_info['zfy'];//总费用
            }elseif($type==2){//下载统计信息
                $data[$k][id]           = $goods_info['id'];//序号
                $data[$k][cxh]          = $goods_info['cxh'];//查新号
                $data[$k][xmmc]         = $goods_info['xmmc'];//项目名称（中文）
                $data[$k][wtrname]      = $goods_info['wtrname'];//委托人姓名
                $data[$k][intime]       = $goods_info['intime'];//委托日期
                $data[$k][process_id]   = getTitleByProcessId($goods_info['process_id']);//处理状态
            }elseif($type==3){
                $data[$k][id]           = $goods_info['id'];//序号
                $data[$k][name]         = $goods_info['name'];//馆员名称
                $data[$k][role_name]    = $goods_info['role_name'];//管员角色
                $data[$k][sf_num]       = $goods_info['sf_num'];//收费工作量
                $data[$k][cx_num]       = $goods_info['cx_num'];//查新工作量
                $data[$k][sh_num]       = $goods_info['sh_num'];//审核工作量
            }elseif($type==4){
                $data[$k][title]        = $goods_info['title'];//查新范围
                $data[$k][num]          = $goods_info['num'];//数量
            }elseif($type==5){
                $data[$k][title]        = $goods_info['title'];//查新目的
                $data[$k][num]          = $goods_info['num'];//数量
            }

        }
        foreach ($data as $field=>$v){
            if($type==1){
                if($field == 'wtrname'){
                    $headArr[]='委托人姓名';
                }

                if($field == 'wtdw'){
                    $headArr[]='委托单位';
                }

                if($field == 'wtremail'){
                    $headArr[]='委托人邮箱';
                }

                if($field == 'xmmc'){
                    $headArr[]='项目名称（中文）';
                }

                if($field == 'xmmc'){
                    $headArr[]='项目名称（英文）';
                }

                if($field == 'cxmd'){
                    $headArr[]='查新目的';
                }

                if($field == 'xxcxmd'){
                    $headArr[]='详细查新目的';
                }

                if($field == 'cxfw'){
                    $headArr[]='查新地域';
                }

                if($field == 'xmjb'){
                    $headArr[]='项目级别';
                }

                if($field == 'lqrq'){
                    $headArr[]='期望完成日期';
                }

                if($field == 'fkfs'){
                    $headArr[]='付款方式';
                }

                if($field == 'kpdw'){
                    $headArr[]='发票抬头';
                }

                if($field == 'qbfs'){
                    $headArr[]='取报告方式';
                }

                if($field == 'txdz'){
                    $headArr[]='通信地址';
                }

                if($field == 'lxryzbm'){
                    $headArr[]='邮政编码';
                }

                if($field == 'show_add_cxd'){
                    $headArr[]='科学技术要点';
                }

                if($field == 'cxyq'){
                    $headArr[]='查新要求';
                }

                if($field == 'keywords_cn'){
                    $headArr[]='检索词';
                }

                if($field == 'contents'){
                    $headArr[]='其他说明';
                }

                if($field == 'intime'){
                    $headArr[]='委托日期';
                }

                if($field == 'zs_user_name'){
                    $headArr[]='完成人';
                }

                if($field == 'cxh'){
                    $headArr[]='查新号';
                }

                if($field == 'zfy'){
                    $headArr[]='总费用';
                }
                $date = date("Y",time());
                $fileName = "{$date}年度查新统计报告.xls";
            }elseif($type==2){
                if($field == 'id'){
                    $headArr[]='序号';
                }

                if($field == 'cxh'){
                    $headArr[]='查新号';
                }

                if($field == 'xmmc'){
                    $headArr[]='项目名称（中文）';
                }

                if($field == 'wtrname'){
                    $headArr[]='委托人姓名';
                }

                if($field == 'intime'){
                    $headArr[]='委托日期';
                }

                if($field == 'process_id'){
                    $headArr[]='处理状态';
                }
                $fileName = "统计信息下载.xls";
            }elseif($type==3){
                if($field == 'id'){
                    $headArr[]='序号';
                }

                if($field == 'name'){
                    $headArr[]='馆员名称';
                }

                if($field == 'role_name'){
                    $headArr[]='管员角色';
                }

                if($field == 'sf_num'){
                    $headArr[]='收费工作量';
                }

                if($field == 'cx_num'){
                    $headArr[]='查新工作量';
                }

                if($field == 'sh_num'){
                    $headArr[]='审核工作量';
                }
                $fileName = "简单统计信息下载.xls";
            }elseif($type==4){
                if($field == 'title'){
                    $headArr[]='查新范围';
                }
                if($field == 'num'){
                    $headArr[]='数量';
                }
                $fileName = "查新范围统计信息下载.xls";
            }elseif($type==5){
                if($field == 'title'){
                    $headArr[]='查新目的';
                }
                if($field == 'num'){
                    $headArr[]='数量';
                }
                $fileName = "查新目的统计信息下载.xls";
            }

        }
        $this->getExcel($fileName,$headArr,$data);
    }

    /*
     *生成excel
     */
    private  function getExcel($fileName,$headArr,$data){
        vendor("PHPExcel.PHPExcel");
       /* $date = date("Y",time());
        $fileName = "{$date}年度查新统计报告.xls";*/
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){
            $span = ord("A");
            foreach($rows as $keyName=>$value){
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);

        //$objPHPExcel->getActiveSheet()->setTitle('test');
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 获取查新目的
     * @param $cxmd
     * @return string
     */
    function getCxmds($cxmd){
        $r = getCxmdCheckbox();
        $cxmd = explode(',',$cxmd);
        $str = '';
        foreach($r as $k=>$v){
            if(in_array($k,$cxmd)){
                $str .= $v.';';
            }
        }
        return $str;
    }

    /**
     * 获取查新要求
     * @param $cxyq
     * @return string
     */
    function getCxyq($cxyq){
        $r = getCxyqCheckbox();
        $cxmd = explode(',',$cxyq);
        $str = '';
        foreach($r as $k=>$v){
            if(in_array($k,$cxmd)){
                $str .= $v.';';
            }
        }
        return $str;
    }
    /**
     * 获取查新地域
     * @param int $cxfw
     * @return string
     */
    function getArea($cxfw=0){
        $area = '';
        if($cxfw){
            switch($cxfw){
                case 1:
                    $area = '国内';
                    break;
                case 2:
                    $area = '国外';
                    break;
                case 3:
                    $area = '国内外';
                    break;
                default:
                    $area = '';
                    break;
            }
        }else{
            $area = '';
        }
        return $area;
    }

    /**
     * 获取查新项目级别
     * @param int $level
     * @return string
     */
    function getLevel($level=0){
        switch($level){
            case 1:
                $str = '国家级';
                break;
            case 2:
                $str = '省部级';
                break;
            case 3:
                $str = '市级';
                break;
            case 4:
                $str = '其他';
                break;
            default:
                $str = '';
                break;
        }
        return $str;
    }

    /**
     * 简单统计列表
     */
    function simpleCount(){
        $data = I('get.');
		$departmentId = M('User')->where("id=".UID)->getField('department');		
		$map12['school_id'] = $departmentId;
		$sarea = M('school_area')->where($map12)->select();
		$this->assign('sarea', $sarea);
		if($data['sarea']){
			$map['sarea']=$data['sarea'];
		}
        if($data['type']){
            $map = self::getDateTime($data);
            $map['department_id'] = DEPARTMENT_ID;
			
            switch($data['type']){
                case 'fw':
                    $listmd = self::getCxfwList($map);
					$this->assign('type','fw');

                    $this->assign('title','查新范围');
                    $this->assign('_listmd',$listmd);
                    break;
                case 'md'://查新范围 1-可以立项 2-鉴定、验收、评价 3-奖励申报 4-申请专利 5-博硕士论文开题 6-其他
                    $listmd = self::getCxmdList($map);
					$this->assign('type','md');
                    $this->assign('title','查新目的');
                    $this->assign('_listmd',$listmd);
                    break;
                case 'school':
                    $list = self::getCxSchoolList($map);
                    $this->assign('title','委托机构');
                    $this->assign('type','school');
                    $this->assign('_listmd',$list);
                    break;
                case 'intime':
                    $list = self::getCxListByTime($map,'intime');
                    $this->assign('title','委托时间');
                    $this->assign('type','intime');
                    $this->assign('_listmd',$list);
                    break;
                case 'endtime':
                    $list = self::getCxListByTime($map,'intime_13');
                    $this->assign('title','完成时间');
                    $this->assign('type','intime_13');
                    $this->assign('_listmd',$list);
                    break;
                default:
                    $this->getStart($data);
                    break;
            }
            $this->assign('num','数量');
            $this->assign('data',$data);
            $this->assign('meta_title', '简单统计');
            $this->display('countList');
        }else{
            $this->assign('meta_title', '简单统计');
            $this->getStart($data);
        }

    }

    private function getCxList($map, $field){
        $res = M('Kjcx')->where($map)->field($field.' as title,count(id) as num')->group($field)->select();
        return $res;
    }

    private function getCxListByTime($map,$field){
        $res = M('Kjcx')->where($map)->field($field.' as title,count(id) as num')->group("left($field,10)")->select();
        foreach($res as $key=>$it){
            if(empty($it['title'])){
                unset($res[$key]);
            }
            $res[$key]['title'] = substr($it['title'],0,10);
        }
        return $res;
    }

    private function getCxSchoolList($map){
        $res = M('Kjcx')->where($map)->field('wtdw as title,count(id) as num')->group('wtdw')->select();
        return $res;
    }
    /**
     * 开始进入的页面
     * @param $data
     */
    function getStart($data){
        $map['department'] = DEPARTMENT_ID;
        $map['typeid']     = array('neq',0);
        $map['sarea']     = $data['sarea'];
        $list = M('User')->where($map)->select();

        $list = self::getRole($list,$data);

        $this->assign('_list',$list);
        $this->assign('data',$data);
        $this->assign('frist','yes');
        $this->display('countList');
		exit;
    }

    /**
     * 获取该机构下各个人员任务数
     * @param $list
     * @param $data
     * @return mixed
     */
    function getRole($list,$data){
        if(!empty($list)){
            $kjcxModel = M('kjcx');
            foreach($list as $k=>$v){
                if($v['typeid'] != '')
                {
                    $list[$k]['role_name'] = getAuthName($v['typeid']);

                //查新
                    $map_1 = self::getDateTime($data);
                    $map_1['department_id'] = DEPARTMENT_ID;
                    $map_1[cx_user_name]    = $v['id'];
                    $list[$k]['cx_num']     = $kjcxModel->where($map_1)->count();
                //审核
                    $map_2 = self::getDateTime($data);
                    $map_2['department_id'] = DEPARTMENT_ID;
                    $map_2[sh_user_name]    = $v['id'];
                    $list[$k]['sh_num']     = $kjcxModel->where($map_2)->count();
                //收费
                    $map_3 = self::getDateTime($data);
                    $map_3['department_id'] = DEPARTMENT_ID;
                    $map_3[sf_user_name]    = $v['id'];
                    $list[$k]['sf_num']     = $kjcxModel->where($map_3)->count();
                }
            }
        }

        return $list;
    }

    /**
     * 返回时间查新条件
     * @param $data
     * @return mixed
     */
    function getDateTime($data){
        if($data['starttime'] && $data['endtime']){
            $endtime = date('Y-m-d H:i:s',strtotime($data['endtime'])+86400);
            $map['intime']= array(array('gt',$data['starttime']),array('lt',$endtime));
        }

        if($data['starttime'] && !$data['endtime']){
            $map['intime']= array('gt',$data['starttime']);
        }

        if(!$data['starttime'] && $data['endtime']){
            $endtime = date('Y-m-d H:i:s',strtotime($data['endtime'])+86400);
            $map['intime']= array('lt',$endtime);
        }
        return $map;
    }

    /**
     * 根据条件统计查新范围
     * @param $map
     * @return mixed
     */
    function getCxfwList($map){
        $kjcxModel = M('kjcx');
        $r = getArea();
        $i=0;
        foreach($r as $k=>$v){
            $map['cxfw'] = $k;
            $listmd[$i]['title'] = $v;
            $listmd[$i]['num']   = $kjcxModel->where($map)->count();
            $listmd[$i]['cxfw']  = $k;
            $i++;
        }
        return $listmd;
    }

    /**
     * 根据条件统计查新目的
     * @param $map
     * @return mixed
     */
    function getCxmdList($map){
        $kjcxModel = M('kjcx');
        $cxmds = getCxmdCheckbox();
        $i=0;
        foreach($cxmds as $k=>$v){
            $map['cxmd'] = array('LIKE',"%$k%");
            $listmd[$i]['title'] = $v;
            $listmd[$i]['num']   = $kjcxModel->where($map)->count();
            $listmd[$i]['cxfw']  = $k;
            $i++;
        }
        return $listmd;
    }
    /**
     * 下载
     */
    function down(){
        $data = I('get.');
        if($data['type']){
            switch($data['type']){
                case 'fw'://查新范围

                    $map = self::getDateTime($data);
                    $map['department_id'] = DEPARTMENT_ID;
                    $listmd = self::getCxfwList($map);
                    if($listmd){//查新范围统计数据下载
                        $this->dataExport($listmd,4);
                    }else{
                        $this->error('数据为空');
                    }
                    break;
                case 'md'://查新目的
                    $map = self::getDateTime($data);
                    $map['department_id'] = DEPARTMENT_ID;
                    $listmd = self::getCxmdList($map);
                    if($listmd){//查新目的统计数据下载
                        $this->dataExport($listmd,5);
                    }else{
                        $this->error('数据为空');
                    }
                    break;
                case 'user'://查新官员
                    $map['department'] = DEPARTMENT_ID;
                    $map['typeid']     = array('neq',0);
                    $list = M('User')->where($map)->select();
                    $list = self::getRole($list,$data);
                    if($list){
                        $this->dataExport($list,3);
                    }else{
                        $this->error('数据为空');
                    }
                    break;
            }
        }else{
        }
    }
    /**
     * 各人员任务数量
     */
    function info(){
        $id     = I('id');
        $type   = I('type');
        $value = I('value');
        $map['department_id'] = DEPARTMENT_ID;
        $model      = M('kjcx');
        if($id && $type){
            $data       = I('get.');
            $typeList   = self::getTypeGroup();
            $map        = self::getDateTime($data);
            if($data['process_id']){
                $map['process_id'] = $data['process_id'];
            }
            if($data['status'] && $data['param']){
                switch($data['status']){
                    case 'xmmc':
                        $map['xmmc']    = array('LIKE',"%$data[param]%");
                        break;
                    case 'cxh':
                        $map['cxh']     = array('LIKE',"%$data[param]%");
                        break;
                    case 'wtrname':
                        $map['wtrname'] = array('LIKE',"%$data[param]%");
                        break;
                }
            }
            $map['department_id'] = DEPARTMENT_ID;
            switch($type){
                case 'sf';//收费
                    $map['sf_user_name'] = $id;
                    $list = $this->lists($model,$map);
                    break;
                case 'cx';//查新
                    $map['cx_user_name'] = $id;
                    $list = $this->lists($model,$map);
                    break;
                case 'sh';//审核
                    $map['sh_user_name'] = $id;
                    $list = $this->lists($model,$map);
                    break;
                case '查新范围'://查新范围
                    $map['cxfw'] = $id;
                    $list = $this->lists($model,$map);
                    break;
                case '查新目的'://查新目的
                    $map['cxmd'] = array('LIKE',"%$id%");
                    $list = $this->lists($model,$map);
                    break;

            }
        }elseif($type && $value){
            switch($type){
                case 'school':
                    $map['wtdw'] = $value;
                    break;
                case '委托时间':
                    $map['intime'] = array('LIKE',"%$value%");
                    break;
                case '完成时间':
                    $map['intime_13'] = array('LIKE',"%$value%");
                    break;
            }
            $list = $this->lists($model,$map);
        }else{
            $this->error('参数错误');
        }
        $this->assign('typeList',$typeList);
        $this->assign('data',$data);
        $list = self::fomartFileIds($list);
        $this->assign('_list',$list);
        $this->display('info');
    }

    /**
     * @return mixed
     */
    function getTypeGroup(){
        $model = M('kjcx');
        $map['department_id'] = DEPARTMENT_ID;
        $map['process_id']    = array('neq',-2);
        return $model ->field('id,process_id')->where($map)->group('process_id')->select();
    }
}